<meta charset="utf-8">
(#) Use `apply()` on `SharedPreferences`

!!! WARNING: Use `apply()` on `SharedPreferences`
   This is a warning.

Id
:   `ApplySharedPref`
Summary
:   Use `apply()` on `SharedPreferences`
Severity
:   Warning
Category
:   Correctness
Platform
:   Android
Vendor
:   Android Open Source Project
Feedback
:   https://issuetracker.google.com/issues/new?component=192708
Since
:   2.3.0 (March 2017)
Affects
:   Kotlin and Java files
Editing
:   This check runs on the fly in the IDE editor
Implementation
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/CleanupDetector.kt)
Tests
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/CleanupDetectorTest.kt)

Consider using `apply()` instead of `commit` on shared preferences.
Whereas `commit` blocks and writes its data to persistent storage
immediately, `apply` will handle it in the background.

!!! Tip
   This lint check has an associated quickfix available in the IDE.

(##) Example

Here is an example of lint warnings produced by this check:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~text
src/test/pkg/SharedPrefsTest.java:16:Warning: Consider using apply()
instead; commit writes its data to persistent storage immediately,
whereas apply will handle it in the background [ApplySharedPref]
    editor.commit();
           --------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the source file referenced above:

`src/test/pkg/SharedPrefsTest.java`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~java linenumbers
package test.pkg;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;
import android.content.SharedPreferences; import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
@SuppressWarnings({"ClassNameDiffersFromFileName", "AccessStaticViaInstance", "MethodMayBeStatic"}) public class SharedPrefsTest extends Activity {
    // OK 1
    public void onCreate1(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("foo", "bar");
        editor.putInt("bar", 42);
        editor.commit();
    }

    // OK 2
    public void onCreate2(Bundle savedInstanceState, boolean apply) {
        super.onCreate(savedInstanceState);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("foo", "bar");
        editor.putInt("bar", 42);
        if (apply) {
            editor.apply();
        }
    }

    // OK 3
    public boolean test1(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("foo", "bar");
        editor.putInt("bar", 42);
        editor.apply(); return true;
    }

    // Not a bug
    public void test(Foo foo) {
        Bar bar1 = foo.edit();
        Bar bar2 = Foo.edit();
        Bar bar3 = edit();


    }

    // Bug
    public void bug1(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("foo", "bar");
        editor.putInt("bar", 42);
    }

    // Constructor test
    public SharedPrefsTest(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("foo", "bar");
    }

    private Bar edit() {
        return null;
    }

    private static class Foo {
        static Bar edit() { return null; }
    }

    private static class Bar {

    }
 }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also visit the
[source code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/CleanupDetectorTest.kt)
for the unit tests for this check to see additional scenarios.

The above example was automatically extracted from the first unit test
found for this lint check, `CleanupDetector.testSharedPrefs`.
To report a problem with this extracted sample, visit
https://issuetracker.google.com/issues/new?component=192708.

(##) Suppressing

You can suppress false positives using one of the following mechanisms:

* Using a suppression annotation like this on the enclosing
  element:

  ```kt
  // Kotlin
  @Suppress("ApplySharedPref")
  fun method() {
     beginTransaction(...)
  }
  ```

  or

  ```java
  // Java
  @SuppressWarnings("ApplySharedPref")
  void method() {
     beginTransaction(...);
  }
  ```

* Using a suppression comment like this on the line above:

  ```kt
  //noinspection ApplySharedPref
  problematicStatement()
  ```

* Using a special `lint.xml` file in the source tree which turns off
  the check in that folder and any sub folder. A simple file might look
  like this:
  ```xml
  &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;lint&gt;
      &lt;issue id="ApplySharedPref" severity="ignore" /&gt;
  &lt;/lint&gt;
  ```
  Instead of `ignore` you can also change the severity here, for
  example from `error` to `warning`. You can find additional
  documentation on how to filter issues by path, regular expression and
  so on
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/lintxml.md.html).

* In Gradle projects, using the DSL syntax to configure lint. For
  example, you can use something like
  ```gradle
  lintOptions {
      disable 'ApplySharedPref'
  }
  ```
  In Android projects this should be nested inside an `android { }`
  block.

* For manual invocations of `lint`, using the `--ignore` flag:
  ```
  $ lint --ignore ApplySharedPref ...`
  ```

* Last, but not least, using baselines, as discussed
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/baselines.md.html).

<!-- Markdeep: --><style class="fallback">body{visibility:hidden;white-space:pre;font-family:monospace}</style><script src="markdeep.min.js" charset="utf-8"></script><script src="https://morgan3d.github.io/markdeep/latest/markdeep.min.js" charset="utf-8"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility="visible")</script>